<template>
    <el-dialog
        :title="titleMap[state.mode]"
        v-model="state.visible"
        width="900"
        destroy-on-close
        @closed="$emit('closed')"
    >
        <el-form
            :model="form"
            :rules="rules"
            :disabled="state.mode == 'show'"
            ref="dialogFormRef"
            label-width="100px"
            label-position="left"
        >
            <el-form-item label="操作类型" v-if="state.mode == 'edit'">
                <el-radio-group v-model="state.editType">
                    <el-radio-button border label="1">编辑其他</el-radio-button>
                    <el-radio-button border label="2">编辑账号密码</el-radio-button>
                </el-radio-group>
            </el-form-item>

            <el-row :gutter="60">
                <el-col :span="12" v-if="state.mode == 'add' || state.editType == '1'">
                    <el-form-item label="头像" prop="avatar">
                        <kitego-attachment-picker
                            :disabled="state.mode == 'show'"
                            v-model="form.avatar"
                            :limit="1"
                        />
                    </el-form-item>
                    <el-form-item label="排序值" prop="sort">
                        <el-input
                            type="number"
                            v-model="form.sort"
                            placeholder="排序值"
                            clearable
                            class="contentWidth"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="昵称" prop="nickname">
                        <el-input
                            v-model="form.nickname"
                            placeholder="请输入完整的昵称"
                            clearable
                            class="contentWidth"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="真实姓名" prop="realName">
                        <el-input
                            v-model="form.realName"
                            placeholder="请输入完整的真实姓名"
                            clearable
                            class="contentWidth"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone">
                        <el-input
                            type="number"
                            v-model="form.phone"
                            placeholder="请输入完整的手机号"
                            clearable
                            class="contentWidth"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input
                            type="email"
                            v-model="form.email"
                            placeholder="请输入完整邮箱"
                            clearable
                            class="contentWidth"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="所属部门" prop="dept">
                        <el-cascader
                            v-model="form.dept"
                            :options="state.depts"
                            :props="state.deptsProps"
                            clearable
                            style="width: 250px"
                        ></el-cascader>
                    </el-form-item>
                    <el-form-item label="所属角色" prop="roleId">
                        <el-select v-model="form.roleId" multiple filterable class="contentWidth">
                            <el-option
                                v-for="item in groups"
                                :key="item.id"
                                :label="item.label"
                                :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="账号状态" prop="status">
                        <el-radio-group v-model="form.status">
                            <el-radio-button border label="1">启用</el-radio-button>
                            <el-radio-button border label="2">禁用</el-radio-button>
                            <el-radio-button border label="3">待审核</el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="登录账号" prop="account">
                        <el-input
                            v-model="form.account"
                            placeholder="用于登录系统"
                            clearable
                            class="contentWidth"
                        ></el-input>
                    </el-form-item>
                    <template
                        v-if="
                            state.mode == 'add' || (state.mode == 'edit' && state.editType == '2')
                        "
                    >
                        <el-form-item label="登录密码" prop="password">
                            <el-input
                                v-model="form.password"
                                type="password"
                                show-password
                                class="contentWidth"
                                placeholder="修改登录密码"
                            ></el-input>
                            <kitegoPasswordStrength
                                v-model="form.password"
                                class="contentWidth"
                            ></kitegoPasswordStrength>
                            <div class="el-form-item-msg">请输入包含英文、数字的8位以上密码</div>
                        </el-form-item>
                        <el-form-item label="确认密码" prop="password2">
                            <el-input
                                type="password"
                                v-model="form.password2"
                                clearable
                                show-password
                                class="contentWidth"
                                placeholder="请再一次输入登录密码"
                            ></el-input>
                        </el-form-item>
                    </template>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button @click="state.visible = false">取 消</el-button>
            <el-button
                v-if="state.mode != 'show'"
                type="primary"
                :loading="state.isSaving"
                @click="submit()"
                >保 存</el-button
            >
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import setting from '@/api/modules/setting.ts'
import type { FormInstance, FormRules } from 'element-plus'
import type { FormModel, TitleMapModel } from '@/views/setting/user/type.ts'

const emit = defineEmits(['success', 'closed'])

const dialogFormRef = ref<FormInstance>()

const form = reactive<FormModel>({
    id: 0,
    account: '',
    avatar: '',
    realName: '',
    dept: '',
    roleId: [],
    deleteFlag: 0,
    status: 1,
    sort: 0,
    password: '',
    password2: '',
    nickname: '',
    phone: '',
    email: ''
})
const rules = reactive<FormRules>({
    status: [{ required: true, message: '账户状态必填' }],
    account: [{ required: true, message: '请输入登录账号' }],
    sort: [{ required: true, message: '请输入排序值' }],
    nickname: [{ required: true, message: '请输入昵称' }],
    realName: [{ required: true, message: '请输入真实姓名' }],
    password: [
        { required: true, message: '请输入登录密码' },
        {
            validator: (rule, value, callback) => {
                if (form.password2 && form.password2 !== '') {
                    if (!dialogFormRef.value) return
                    dialogFormRef.value.validateField('password2')
                }
                callback()
            }
        }
    ],
    password2: [
        { required: true, message: '请再次输入密码' },
        {
            validator: (rule, value, callback) => {
                if (value !== '' && value !== form.password) {
                    callback(new Error('两次输入密码不一致!'))
                } else {
                    callback()
                }
            }
        }
    ],
    phone: [{ required: true, message: '请输入手机号' }],
    email: [{ required: true, message: '请输入邮箱地址' }],
    dept: [{ required: true, message: '请选择所属部门' }],
    roleId: [{ required: true, message: '请选择所属角色', trigger: 'change' }]
})

const titleMap = reactive<TitleMapModel>({
    add: '新增用户',
    edit: '编辑用户',
    show: '查看'
})

interface GroupsModel {
    [key: string]: string // 添加索引签名
}
const groups = ref<GroupsModel[]>([])

const state = reactive({
    mode: 'add',
    visible: false,
    isSaving: false,
    editType: '1',
    groupsProps: {
        value: 'id',
        label: 'label',
        multiple: true,
        checkStrictly: true
    },
    depts: [],
    deptsProps: {
        value: 'id',
        label: 'label',
        checkStrictly: true
    }
})

watch(
    () => form.dept,
    (dept) => {
        if (Array.isArray(dept)) {
            form.dept = dept[0]
        }
    }
)

onMounted(() => {
    getGroup()
    getDept()
})

// 加载树数据
async function getGroup() {
    groups.value = await setting.role.list.get({ page: 1, pageSize: 10000 })
}

async function getDept() {
    state.depts = await setting.dept.list.get()
}

// 表单提交方法
async function submit() {
    dialogFormRef.value?.validate()
    state.isSaving = true
    const res = await setting.admin.edit.post(form, { await: 1 })
    if (res) {
        emit('success', form, state.mode)
    }
    state.isSaving = false
    state.visible = false
}

function open(mode = 'add') {
    state.mode = mode
    state.visible = true
}

function setData(data: FormModel) {
    form.id = data.id
    form.account = data.account
    form.avatar = data.avatar
    form.nickname = data.nickname
    form.realName = data.realName
    form.roleId = data.roleId
    form.dept = data.dept
    form.phone = data.phone
    form.email = data.email
    form.sort = data.sort
    form.deleteFlag = data.deleteFlag
    form.status = data.status
}

defineExpose({
    open,
    setData
})
</script>

<style scoped lang="scss">
.contentWidth {
    width: 250px;
}
</style>
